import Phaser from 'phaser'
import { GroupBar } from '../ui/GroupBar.js';
import { SoundUtils } from '../utils/SoundUtils.js';

// 单位跃迁台：十进一合成
export class ModeBScene extends Phaser.Scene {
  rangeMode= 'yi'
  totalRounds= 10
  currentRound= 0
  score= 0

  // 教师控制的问答游戏状态
  currentLevel= 0 // 0:万, 1:十万, 2:百万, 3:千万, 4:亿, 5:十亿, 6:百亿
  targetLevel= 4 // 默认目标：亿
  questionType: 'merge' | 'split' = 'merge' // 合成或分解问题
  currentQuestion= ''
  correctAnswer= 10

  // UI元素
  titleText!: Phaser.GameObjects.Text
  questionText!: Phaser.GameObjects.Text
  currentLevelText!: Phaser.GameObjects.Text
  targetLevelText!: Phaser.GameObjects.Text
  mergeButton!: Phaser.GameObjects.Text
  nextQuestionButton!: Phaser.GameObjects.Text
  feedbackText!: Phaser.GameObjects.Text
  progressBar!: Phaser.GameObjects.Rectangle
  progressFill!: Phaser.GameObjects.Rectangle
  hudText!: Phaser.GameObjects.Text
  instructionText!: Phaser.GameObjects.Text
  groupBar!: any // 暴露给 MainScene 使用

  // 游戏数据
  levelNames = ['万', '十万', '百万', '千万', '亿', '十亿', '百亿']
  questions = [
    // 基础进位问题
    { from: '万', to: '十万', answer: 10, type: 'merge' as const },
    { from: '十万', to: '百万', answer: 10, type: 'merge' as const },
    { from: '百万', to: '千万', answer: 10, type: 'merge' as const },
    { from: '千万', to: '亿', answer: 10, type: 'merge' as const },
    { from: '亿', to: '十亿', answer: 10, type: 'merge' as const },
    { from: '十亿', to: '百亿', answer: 10, type: 'merge' as const },

    // 跨级进位问题（增加难度）
    { from: '万', to: '百万', answer: 100, type: 'merge' as const },
    { from: '万', to: '千万', answer: 1000, type: 'merge' as const },
    { from: '万', to: '亿', answer: 10000, type: 'merge' as const },
    { from: '十万', to: '千万', answer: 100, type: 'merge' as const },
    { from: '十万', to: '亿', answer: 1000, type: 'merge' as const },
    { from: '百万', to: '亿', answer: 100, type: 'merge' as const },

    // 分解问题
    { from: '十万', to: '万', answer: 10, type: 'split' as const },
    { from: '百万', to: '十万', answer: 10, type: 'split' as const },
    { from: '千万', to: '百万', answer: 10, type: 'split' as const },
    { from: '亿', to: '千万', answer: 10, type: 'split' as const },
    { from: '亿', to: '万', answer: 10000, type: 'split' as const },
    { from: '千万', to: '万', answer: 1000, type: 'split' as const }
  ]

  constructor() {
    super('ModeBScene')
  }

  init(data) {
    this.rangeMode = data.rangeMode || 'yi'
    this.totalRounds = data.totalRounds || 10
    this.setTargetLevel()
  }

  create() {
    console.log('ModeBScene created with range:', this.rangeMode)

    // 初始化音效
    SoundUtils.init()

    // 监听场景关闭事件，清理延时调用
    this.events.once('shutdown', () => {
      this.time.removeAllEvents()
      if (this.gameTimer) {
        this.gameTimer.destroy()
      }
    })

    // 监听变化
    this.events.on('rangeChanged', (newRange) => {
      this.rangeMode = newRange
      this.setTargetLevel()
      this.resetAll()
    })
    this.events.on('roundsChanged', (val) => {
      this.totalRounds = val
      this.resetAll()
    })

    this.createUI()
    this.resetAll()
  }

  setTargetLevel() {
    switch (this.rangeMode) {
      case 'yi':
        this.targetLevel = 4 // 亿
        break
      case 'shiyi':
        this.targetLevel = 5 // 十亿
        break
      case 'baiyi':
        this.targetLevel = 6 // 百亿
        break
    }
  }

  createUI() {
    // 直接在游戏场景顶部添加切换按钮
    this.createInGameMenu()

    // 标题
    this.titleText = this.add.text(160, 100, '单位跃迁台：十进制问答', {
      fontSize: '28px', color: '#22D3EE', fontFamily: 'Arial, sans-serif'
    })

    // HUD（轮次和分数）
    this.hudText = this.add.text(1120, 60, '', { fontSize: '18px', color: '#9CA3AF' }).setOrigin(1,0)

    // 删除教师指导说明

    // 当前问题显示
    this.questionText = this.add.text(640, 180, '', {
      fontSize: '28px', color: '#FDE047', fontFamily: 'Arial, sans-serif',
      align: 'center'
    }).setOrigin(0.5)

    // 删除当前级别和教学目标提示

    // 进度条 - 位置上移
    this.progressBar = this.add.rectangle(640, 250, 520, 20, 0x374151)
    this.progressFill = this.add.rectangle(380, 250, 0, 20, 0x10B981).setOrigin(0, 0.5)

    // 教师操作按钮 - 位置上移
    this.mergeButton = this.add.text(480, 320, '✅ 学生答对了', {
      fontSize: '20px', color: '#FFFFFF', backgroundColor: '#059669', padding: { x: 25, y: 15 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    this.nextQuestionButton = this.add.text(800, 320, '➡️ 下一题', {
      fontSize: '20px', color: '#FFFFFF', backgroundColor: '#2563EB', padding: { x: 25, y: 15 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    // 按钮事件
    this.mergeButton.on('pointerdown', () => this.onCorrectAnswer())
    this.nextQuestionButton.on('pointerdown', () => this.nextQuestion())

    // 反馈文本 - 位置上移
    this.feedbackText = this.add.text(640, 380, '', { fontSize: '20px', color: '#FDE047' }).setOrigin(0.5)

    // 删除游戏说明

    // 装饰
    this.createDecorations()

    // 小组竞赛条
    this.groupBar = new GroupBar(this, 20, 620, 1240, 'star')
    this.add.existing(this.groupBar)

    // 添加重置成绩按钮
    this.createResetButton()

    // 开始游戏
    this.resetAll()
  }

  // 游戏专用键盘控制（空格和A键）
  setupGameKeyboardControls() {
    this.input.keyboard?.on('keydown', (e) => {
      // 游戏控制
      if (e.key === ' ') { // 空格键手动合成
        e.preventDefault()
        this.performMerge()
      }
      if (e.key.toLowerCase() === 'a') { // A键切换自动合成
        this.toggleAutoMerge()
      }
    })
  }

  setDifficulty(difficulty: 'easy' | 'medium' | 'hard') {
    this.difficulty = difficulty

    // 更新难度按钮样式
    this.difficultyButtons.forEach((btn, index) => {
      const difficulties = ['easy', 'medium', 'hard']
      const isActive = difficulties[index] === difficulty
      btn.setStyle({
        color: isActive ? '#FDE047' : '#D9E8FF',
        backgroundColor: isActive ? '#374151' : '#2D3748'
      })
    })

    // 根据难度调整游戏参数
    switch (difficulty) {
      case 'easy':
        this.timeLimit = 45
        this.bonusMultiplier = 1
        break
      case 'medium':
        this.timeLimit = 30
        this.bonusMultiplier = 1.5
        break
      case 'hard':
        this.timeLimit = 20
        this.bonusMultiplier = 2
        break
    }

    this.feedbackText.setText(`难度设置为：${difficulty === 'easy' ? '简单' === 'medium' ? '中等' : '困难'}`)
  }

  toggleAutoMerge() {
    this.autoMergeEnabled = !this.autoMergeEnabled

    this.autoMergeButton.setStyle({
      backgroundColor: this.autoMergeEnabled ? '#059669' : '#2D3748',
      color: this.autoMergeEnabled ? '#FFFFFF' : '#D9E8FF'
    })

    this.feedbackText.setText(this.autoMergeEnabled ? '自动合成已开启' : '自动合成已关闭')

    if (this.autoMergeEnabled) {
      this.startAutoMerge()
    }
  }

  startAutoMerge() {
    if (!this.autoMergeEnabled) return

    // 每2秒自动合成一次
    this.time.delayedCall(2000, () => {
      if (this.autoMergeEnabled && this.currentUnits >= this.mergeCosts[this.currentLevel]) {
        this.performMerge()
        this.startAutoMerge() // 继续自动合成
      } else if (this.autoMergeEnabled) {
        this.startAutoMerge() // 继续检查
      }
    })
  }

  createInGameMenu() {
    // 简单的模式切换按钮
    const modeA = this.add.text(120, 70, '→ 黑洞纠错台', {
      fontSize: '16px', color: '#22D3EE', backgroundColor: '#1F2937', padding: { x: 10, y: 5 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    const modeC = this.add.text(440, 70, '→ 星际对比跳', {
      fontSize: '16px', color: '#22D3EE', backgroundColor: '#1F2937', padding: { x: 10, y: 5 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    modeA.on('pointerdown', () => {
      console.log('Switching to ModeAScene from ModeB')
      SoundUtils.playTransition()
      this.scene.switch('ModeAScene', { rangeMode: this.rangeMode, totalRounds: this.totalRounds })
    })
    modeC.on('pointerdown', () => {
      console.log('Switching to ModeCScene from ModeB')
      SoundUtils.playTransition()
      this.scene.switch('ModeCScene', { rangeMode: this.rangeMode, totalRounds: this.totalRounds })
    })
  }

  createDecorations() {
    // 添加能量粒子效果
    for (let i = 0; i < 15; i++) {
      const x = Math.random() * 1280
      const y = Math.random() * 720
      const particle = this.add.circle(x, y, Math.random() * 3 + 1, 0x22D3EE, 0.4)
      
      // 浮动动画
      this.tweens.add({
        targets,
        y: y - 50,
        alpha: 0.1,
        duration: 3000 + Math.random() * 2000,
        repeat: -1,
        yoyo,
        ease: 'Sine.easeInOut'
      })
    }

    // 跃迁门装饰
    const portal = this.add.circle(1100, 200, 40, 0x4C1D95, 0.3)
    this.tweens.add({
      targets,
      scaleX: 1.3,
      scaleY: 1.3,
      alpha: 0.1,
      duration: 1500,
      yoyo,
      repeat: -1,
      ease: 'Sine.easeInOut'
    })
  }

  resetAll() {
    this.currentRound = 0
    this.score = 0
    this.currentLevel = 0
    this.nextQuestion()
  }

  nextQuestion() {
    if (this.currentRound >= this.totalRounds) {
      SoundUtils.playRoundEnd()
      this.feedbackText.setText(`本轮结束！得分：${this.score}/${this.totalRounds}`)
      this.mergeButton.setText('点击重新开始')
      this.mergeButton.setStyle({ backgroundColor: '#059669' })
      this.mergeButton.removeAllListeners()
      this.mergeButton.setInteractive({ useHandCursor: true }).once('pointerdown', () => this.resetAll())
      return
    }

    this.currentRound++
    this.generateQuestion()
    this.updateUI()
  }

  generateQuestion() {
    // 根据当前级别生成问题
    const availableQuestions = this.questions.filter(q => {
      const fromLevel = this.levelNames.indexOf(q.from)
      const toLevel = this.levelNames.indexOf(q.to)
      return fromLevel <= this.targetLevel && toLevel <= this.targetLevel
    })

    if (availableQuestions.length === 0) {
      // 如果没有可用问题，使用基础问题
      this.currentQuestion = `多少个万等于1个十万？`
      this.correctAnswer = 10
      this.questionType = 'merge'
    } else {
      const question = availableQuestions[Math.floor(Math.random() * availableQuestions.length)]
      if (question.type === 'merge') {
        this.currentQuestion = `多少个${question.from}等于1个${question.to}？`
      } else {
        this.currentQuestion = `1个${question.from}等于多少个${question.to}？`
      }
      this.correctAnswer = question.answer
      this.questionType = question.type
    }
  }

  onCorrectAnswer() {
    // 学生答对了
    this.score++

    // 播放正确音效
    SoundUtils.playCorrect()

    // 如果是合成问题，提升级别
    if (this.questionType === 'merge' && this.currentLevel < this.targetLevel) {
      this.currentLevel++
    }

    this.feedbackText.setText('✅ 很好！学生答对了')
    this.feedbackText.setColor('#10B981')

    // 1.5秒后自动进入下一题
    this.time.delayedCall(1500, () => {
      if (this.scene.isActive()) {
        this.nextQuestion()
      }
    })

    this.updateUI()
  }

  updateUI() {
    // 更新HUD
    this.hudText.setText(`第 ${this.currentRound}/${this.totalRounds} 题  |  得分 ${this.score}`)

    // 更新问题显示
    this.questionText.setText(this.currentQuestion)

    // 更新进度条（基于题目进度而不是级别进度）
    const progress = this.currentRound / this.totalRounds
    this.progressFill.width = Math.max(0, progress * 520)

    // 清空反馈文本（除非是结束状态）
    if (this.currentRound <= this.totalRounds) {
      this.feedbackText.setText('')
    }
  }



  showMergeEffect() {
    // 创建合成特效
    const particles: Phaser.GameObjects.Arc[] = []
    
    for (let i = 0; i < 10; i++) {
      const angle = (i / 10) * Math.PI * 2
      const startX = 640 + Math.cos(angle) * 100
      const startY = 360 + Math.sin(angle) * 100
      
      const particle = this.add.circle(startX, startY, 5, 0x22D3EE)
      particles.push(particle)
      
      // 粒子向中心聚集
      this.tweens.add({
        targets,
        x: 640,
        y: 360,
        scaleX: 0.1,
        scaleY: 0.1,
        duration: 500,
        ease: 'Power2',
        onComplete: () => {
          particle.destroy()
        }
      })
    }
    
    // 中心爆发效果
    this.time.delayedCall(500, () => {
      const burst = this.add.circle(640, 360, 20, 0xFDE047, 0.8)
      this.tweens.add({
        targets,
        scaleX: 3,
        scaleY: 3,
        alpha: 0,
        duration: 300,
        onComplete: () => {
          burst.destroy()
        }
      })
    })
  }

  // 创建重置成绩按钮
  createResetButton() {
    const resetBtn = this.add.text(1200, 580, '🔄 重置成绩', {
      fontSize: '16px', color: '#FFFFFF', backgroundColor: '#DC2626',
      padding: { x: 12, y: 8 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    // 悬停效果
    resetBtn.on('pointerover', () => {
      resetBtn.setStyle({ backgroundColor: '#B91C1C' })
    })
    resetBtn.on('pointerout', () => {
      resetBtn.setStyle({ backgroundColor: '#DC2626' })
    })

    // 点击事件
    resetBtn.on('pointerdown', () => {
      this.showResetConfirmation()
    })
  }

  // 显示重置确认对话框
  showResetConfirmation() {
    // 创建半透明背景
    const overlay = this.add.rectangle(640, 360, 1280, 720, 0x000000, 0.7)
    overlay.setInteractive()

    // 创建确认对话框
    const dialog = this.add.container(640, 360)
    const dialogBg = this.add.rectangle(0, 0, 400, 200, 0x1F2937)
    const dialogBorder = this.add.rectangle(0, 0, 400, 200).setStrokeStyle(2, 0x374151)

    const title = this.add.text(0, -60, '确认重置', { fontSize: '24px', color: '#FDE047' }).setOrigin(0.5)
    const message = this.add.text(0, -20, '确定要清除所有队伍的成绩吗？', { fontSize: '16px', color: '#D9E8FF' }).setOrigin(0.5)

    const confirmBtn = this.add.text(-80, 40, '确定', {
      fontSize: '18px', color: '#FFFFFF', backgroundColor: '#DC2626', padding: { x: 20, y: 10 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    const cancelBtn = this.add.text(80, 40, '取消', {
      fontSize: '18px', color: '#FFFFFF', backgroundColor: '#6B7280', padding: { x: 20, y: 10 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    dialog.add([dialogBg, dialogBorder, title, message, confirmBtn, cancelBtn])

    // 确定按钮事件
    confirmBtn.on('pointerdown', () => {
      this.groupBar.resetAll()
      overlay.destroy()
      dialog.destroy()
      console.log('单位跃迁台成绩已重置')
    })

    // 取消按钮事件
    cancelBtn.on('pointerdown', () => {
      overlay.destroy()
      dialog.destroy()
    })

    // 点击背景关闭
    overlay.on('pointerdown', () => {
      overlay.destroy()
      dialog.destroy()
    })
  }

  destroy() {
    this.events.off('rangeChanged')
    super.destroy()
  }
}
